package com.leetcode.题库;

import com.leetcode.common.model.ListNode;

/**
 * @author 覃国强
 * @date 2022-02-26 20:33
 */
public class 题库_0019_删除链表的倒数第N个结点 {

  static
  class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
      if (head == null) {
        return head;
      }

      int length = length(head);
      // 获取删除节点的正数个数
      n = length - n + 1;
      if (n == 1) {
        return head.next;
      }
      ListNode prev = null;
      ListNode node = head;
      while (n > 1) {
        prev = node;
        node = node.next;
        --n;
      }

      if (prev == null) {
        return head.next;
      }

      prev.next = node.next;

      return head;
    }

    private int length(ListNode head) {
      int length = 0;
      while (head != null) {
        ++length;
        head = head.next;
      }
      return length;
    }

  }

}
